package com.step.ems.pages.elevator

import android.util.Log
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.step.ems.Destinations.ID
import com.step.ems.api.ApiService
import com.step.ems.api.res.ElevatorDetailRes
import com.step.ems.common.UiState
import com.step.ems.common.launch
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

@HiltViewModel
class ElevatorDetailViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val apiService: ApiService
) : ViewModel() {
    val id = savedStateHandle.get<Int>(ID) ?: 0

    private val _uiState = MutableStateFlow<UiState>(UiState.Empty)
    val uiState = _uiState.asStateFlow()

    private val _data = MutableStateFlow(ElevatorDetailRes())
    val data get() = _data.asStateFlow()

    init {
        Log.d("ElevatorDetailViewModel", "id: $id")
        getData()
    }

    private fun getData() {
        launch(
            state = _uiState,
            delayTime = 200,
            onStart = {
                _uiState.value = UiState.Loading()
            }) {
            _data.value = apiService.elevatorDetail(id).get()
            _uiState.value = UiState.Success
        }
    }
}